package com.dbh.alg.datastructure.queue;

import cn.hutool.core.lang.tree.Tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树层序遍历
 * @author 董帮辉
 * @date 2025/5/17
 **/
public class E01Leetcode102 {

    /**
     * 按层级遍历二叉树
     * @param root 根节点
     * @return 遍历后的集合
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedListQueue<>();
        queue.offer(root);
        int c1 = 1; // 当前层节点数
        while(!queue.isEmpty()) {
            int c2 = 0; // 下一层节点数
            List<Integer> level = new ArrayList<>(); // 保存每一层结果
            for (int i = 0; i< c1; i++) {
                TreeNode poll = queue.poll();
                level.add(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                    c2++;
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                    c2++;
                }
            }
            System.out.println();
            c1 = c2;
            list.add(level);
        }
        return list;
    }

    public static void main(String[] args) {

        /**
         *                 1
         *               /  \
         *              2    3
         *            / \   / \
         *           4  5  6   7
         *
         */
        TreeNode root = new TreeNode(new TreeNode(new TreeNode(null,4,null),2,
                new TreeNode(null,5,null)),
                1,
                new TreeNode(new TreeNode(null,6,null),3,
                        new TreeNode(null,7,null)));
        Queue<TreeNode> queue = new ArrayQueue<>(7);
        queue.offer(root);
        int c1 = 1;
        while(!queue.isEmpty()) {
            int c2 = 0;
            for (int i = 0; i< c1; i++) {
                TreeNode poll = queue.poll();
                System.out.print(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                    c2++;
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                    c2++;
                }
            }
            System.out.println();
            c1 = c2;
        }

    }

}
